//
//  HLTabBar.swift
//  MyBlog
//
//  Created by 李芙蓉 on 16/3/4.
//  Copyright © 2016年 hanlei. All rights reserved.
//

import UIKit

class HLTabBar: UITabBar {
    
    var composeCallBack : ((button:UIButton)->())?

    //懒加载一个composeButton
    private lazy var composeButton: UIButton = {
        
        let button = UIButton()
        
        button.addTarget(self, action: "composeButtonDidClick", forControlEvents: .TouchUpInside)
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        
        button.sizeToFit()
        
        return button
    }()
    
    //重写构造方法
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        addSubview(composeButton)
    }
    
    //布局子控件
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        composeButton.center = CGPoint(x: self.center.x, y: bounds.size.height/2)
        
        let vWidth = bounds.width/5
        
        var index = 0
        
        //取出tableView中的所有类型为tabBarButton的子控件，加上composeButton重新排列
        for v in subviews {
            
            if v.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                
                v.frame = CGRect(x: CGFloat(index) * vWidth, y: 0, width: vWidth, height: bounds.height)
                
                index = index == 1 ? index+2 : index+1
                
            }
        }
    }
    
    //composeButton的点击事件
    //如果不加上@objc运行循环不能监听这个私有点击事件，其他事件同理
    @objc private func composeButtonDidClick () {
        
        composeCallBack?(button: composeButton)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
